package com.aca.market.controller;


import com.aca.market.entity.*;
import com.aca.market.service.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 购物车表 前端控制器
 * </p>
 *
 * @author aca
 * @since 2020-11-16
 */
@Controller
@Slf4j
public class CartController {

    @Autowired
    ICartService cartService;
    @Autowired
    IUserService userService;
    @Autowired
    IAddressService addressService;
    @Autowired
    IIndentService indentService;
    @Autowired
    IIndentItemService iiService;
    @Autowired
    IItemService itemService;

    @GetMapping({"/cart/","/cart"})
    public String toCart(Model model){
        //商品：数量
        Map<Item,Integer> userCart = null;
        //获取当前用户
        User user = userService.nowUser();
        if (user != null){
            //getUserCart每次获取都能更新sessionCart
            userCart = cartService.getUserCart();
            log.info("=====MAP: " + userCart);
            model.addAttribute("cart",userCart);
            return "cart";
        }
        return "login";
    }

    @GetMapping("/cart/checkout")
    public String toCheckout(Model model){
        //创建订单 锁定库存 等用户完善下单信息
        //1 把购物车的商品映射到结算页面
        Session session = userService.nowSession();
        User user = userService.nowUser();
        if (user != null){
            //也更新了库存
            Map<Item,Integer> userCart = cartService.getUserCart();
            if (!userCart.isEmpty()){
                log.info("*******"+userCart);
                model.addAttribute("cart",userCart);
                //2 把用户所拥有的地址也传给页面
                List<Address> addressList = addressService.list
                        (new QueryWrapper<Address>().eq("user_id", user.getId()));
                log.info("********"+addressList);
                model.addAttribute("address",addressList);
                return "checkout";
            }
        }
        //在跳转到登录页后显示（未做
        session.setAttribute("err-user","请先登录！");
        return "login";
    }

    @GetMapping("/cart/checkout/{userName}")
    public String toCheckoutWithName(@PathVariable("userName") String userName, Model model){
        //创建订单 锁定库存 等用户完善下单信息
        //1 把购物车的商品映射到结算页面
        Long member = 0L;
        if (userService.getOne(new QueryWrapper<User>().eq("username",userName))!=null){
            member = 1L;
        }

        Session session = userService.nowSession();
        User user = userService.nowUser();
        if (user != null){
            //也更新了库存
            Map<Item,Integer> userCart = cartService.getUserCart();
            if (!userCart.isEmpty()){
                log.info("*******"+userCart);
                model.addAttribute("cart",userCart);
                //2 把用户所拥有的地址也传给页面
                List<Address> addressList = addressService.list
                        (new QueryWrapper<Address>().eq("user_id", user.getId()));
                log.info("********"+addressList);
                model.addAttribute("address",addressList);
                model.addAttribute("member",member);
                return "checkout";
            }
        }
        //在跳转到登录页后显示（未做
        session.setAttribute("err-user","请先登录！");
        return "login";
    }

    @PostMapping("/cart/payment")
    @ResponseBody
    public Long toPay(@RequestBody Indent indent){
        return indentService.paySteps(indent);
    }

    @GetMapping(value = "/cart/checkAmount")
    @ResponseBody
    public String checkCart(){
        Integer amount = cartService.checkCartAmount();
        return String.valueOf(amount);
    }

//    @GetMapping("/invoice")
//    //对应订单id下的小票页
//    public String toInvoice(@RequestParam Long indentId,Model model){
//        List<IndentItem> res = iiService.list(new QueryWrapper<IndentItem>().eq("indent_id", indentId));
//        model.addAttribute("items",res);
//        model.addAttribute("indentId",indentId);
//        //nome 这东西就应该前端做
//        model.addAttribute("allPrice",indentService.getById(indentId).getPayment());
//        return "invoice";
//    }

    @ResponseBody
    @RequestMapping(value="/cart/verifyUserExist",method= RequestMethod.GET)
    public String verifyAddUser(@RequestParam("userName") String userName){
        if(userService.getOne(new QueryWrapper<User>().eq("username",userName))==null)
            return "null";
        return "true";
    }

    @GetMapping("/cart/invoice")
    //对应订单id下的小票页
    public String toInvoice(@RequestParam Long indentId,@RequestParam String tag ,Model model){
        List<IndentItem> res = iiService.list(new QueryWrapper<IndentItem>().eq("indent_id", indentId));
        Double memberPrice = 0.0;
        System.out.println("--------------------------------------->>>>>>>>>>>>>>>>>>>>>>>>==============>"+tag);
        for(IndentItem i:res){
            Item item=itemService.getById(i.getItemId());
            if(item.getType()==2&&"Yes".equals(tag))
                memberPrice += Double.parseDouble(item.getPriceSell().toString())*0.9*i.getCount();
            else
                memberPrice += Double.parseDouble(item.getPriceSell().toString())*i.getCount();
        }
        model.addAttribute("items",res);
        model.addAttribute("indentId",indentId);
        model.addAttribute("normalPrice",indentService.getById(indentId).getPayment());
        model.addAttribute("memberPrice",memberPrice);
        model.addAttribute("tag",tag);  //送到小票判断是否为会员，Yes就是会员
        return "invoice";
    }
}

